package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

/*
* 执行DML操作
* DML:INSERT,UPDATE,DELETE
*
* */
public class JDBCDemo2 {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");//mysql的驱动
            //2.与数据库建立连接
            Connection connection = DriverManager.getConnection(
                    //url格式是固定的     数据库地址     /数据库名?参数
                    "jdbc:mysql://localhost:3306/tedu?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true",
                    "root",
                    "root"
            );
            System.out.println("与数据库建立连接！");
            //通过连接对象创建用于执行SQL语句的语句对象
            Statement statement = connection.createStatement();
            //向userinfo表中插入一条记录
//            String sql="INSERT INTO userinfo (username,password,nickname,age) " +
//                    " VALUES ('张三','123456','阿三',22);";
            /*
            * Statement提供的方法：
            * int executeUpdate(String sql)
            * 专门用于执行DML语句的，返回值表达执行该DML后影响了表中多少条记录*/
            Scanner scanner= new Scanner(System.in);
            System.out.println("欢迎注册");
            System.out.println("请输入用户名");
            String username = scanner.nextLine();
            System.out.println("请输入密码");
            String password = scanner.nextLine();
            System.out.println("请输入昵称");
            String nickname = scanner.nextLine();
            System.out.println("请输入年龄");
            int age = scanner.nextInt();
            String sql="INSERT INTO userinfo (username,password,nickname,age) " +
                    " VALUES ('"+username+"','"+password+"','"+nickname+"',"+age+");";
            int num = statement.executeUpdate(sql);
            if(num>0){
                System.out.println("插入成功");
            }else{
                System.out.println("插入失败");
            }
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
